import logging

from flask import current_app, jsonify
from flask import g
from flask import request
from flask import session
from info import redis_store
from info.constants import CLICK_RANK_MAX_NEWS
from info.models import User, News, Category
from info.utils.common import user_login_data
from info.utils.response_code import RET
from . import index_blu
from flask import render_template

@index_blu.route('/newslist')
def news_list():
    # 首页新闻列表展示
    # 1.获取参数
    # 2.校验参数
    # 3.查询数据
    # 4.返回数据
    cid = request.args.get('cid','1')
    page= request.args.get('page','1')
    per_page = request.args.get('per_page',10)
    try:
        cid = int(cid)
        page = int(page)
        per_page = int(per_page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno = RET.PARAERR,errmsg = '参数错误')

    filters = [News.status == 0]
    if cid != 1:
        filters.append(News.category_id==cid)
    try:
        paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page,per_page,False)
        items = paginate.items
        total_pages = paginate.pages
        current_page = paginate.page
    except Exception as  e:
        current_app.logger.error(e)
        return jsonify(errno = RET.DBERR,errmsg = '数据查询失败')

    news_li = []
    for news in items:
        news_li.append(news.to_basic_dict())

    data = {
        'currentPage':current_page,
        'total_page':total_pages,
        'newsList':news_li
    }


    return jsonify(errno = RET.OK,errmsg = 'OK',data = data)

@index_blu.route("/")
@user_login_data
def index():

    # 1.右上角显示用户的登录信息
    # 从浏览器获取session中的user_id
    # 校验,如果存在此用户则显示头像


    # user.to_dict()

    # 2.实现右侧排行榜
    # 定义一个对象列表
    new_dict = []
    try :
        new_dict = News.query.order_by(News.clicks.desc()).limit(CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)
    # 定义一个字符串列表
    news_dict_li = []

    for news in new_dict:
        news_dict_li.append(news.to_basic_dict())

    # 首页分类栏显示
    catagories =  Category.query.all()
    cate_dict = []

    for category in catagories:
        cate_dict.append(category.to_dict())

    data = {
        'user_info': g.user.to_dict() if g.user else None,
        'news_dict_li':news_dict_li,
        'categories':cate_dict
    }
    return render_template("news/index.html",data = data)


@index_blu.route("/favicon.ico")
def favicon():

    return current_app.send_static_file("news/favicon.ico")